package controllers;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.mail.EmailException;

import controllers.Entity;

import models.Email;
import models.Entities;
import models.Idea;
import models.Organization;
import models.Permission;
import models.Tag;
import models.Topic;
import models.User;
import play.db.jpa.JPABase;
import play.mvc.Controller;

/**
 * PostingIdea Controller in order to handle creation of ideas and adding them
 * to topic/entity/organization
 * 
 * @author Ghada Abu Shady
 */
public class PostingIdea extends Controller {
	/**
	 * temporary list of mergedidea
	 * 
	 * @author youstina galal
	 */
	public static List<Idea> idea = new LinkedList<Idea>();
	/**
	 * topic id used in this controller
	 * 
	 * @author youstina galal
	 */
	public static Long topicIdOne;
	/**
	 * The organization id in which topic will be created
	 * 
	 * @author youstina galal
	 */
	public static Long organizationIdOne;
	/**
	 * The entity id in which topic will be created in
	 * 
	 * @author youstina galal
	 */
	public static Long entityIdOne;

	/**
	 * directs to the page where idea title and body are inserted
	 * 
	 * @param topicId
	 *            id of topic that idea will be posted on
	 * @author Ghada Abu Shady
	 */
	public static void Post(Long topicId) {
		// topicId = topicIdId;
		Topic topic = Topic.findById(topicId);
		render(topic);
	}

	/**
	 * directs to the page where idea title and body are inserted
	 * 
	 * @param entityId
	 *            the entity id that the idea will be posted on
	 * @author Ghada Abu Shady
	 */
	public static void PostToEntity(Long entityId) {
		Entities entity = Entities.findById(entityId);
		render(entity);
	}

	/**
	 * directs to the page where idea title and body are inserted
	 * 
	 * @param organizationId
	 *            id of organization that idea will be posted on
	 * @author Ghada Abu Shady
	 */
	public static void PostToOrganization(Long organizationId) {
		Organization organization = Organization.findById(organizationId);
		render(organization);
	}

	/**
	 * displays the idea details and check whether the idea belong to the
	 * user displaying it or not It also checks whether the ideas was marked as
	 * spam before or not
	 * 
	 * @param ideaId
	 *            id of the idea to be displayed
	 * @author Ghada Abu Shady
	 * @author Shahir El Faramawy
	 */
	public static void ShowIdea(Long ideaId) {
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		Idea idea = Idea.findById(ideaId);
		if (idea.author.id == user.id || user.email=="admin@admin.com") {
			showUserIdea(ideaId);
		}
		if (idea.topic != null && user.id == idea.topic.author.id) {
			showIdeaForOrganizer(idea.id);
		}
		if (idea.topic != null) {
			for (int counter = 0; counter < idea.topic.entity.entityOrganizers
					.size(); counter++) {
				if (user.id == idea.topic.entity.entityOrganizers.get(counter).id) {
					showIdeaForOrganizer(idea.id);
				}
			}
		}
		if (idea.topic != null
				&& user.id == idea.topic.entity.organization.lead.id) {
			showIdeaForOrganizer(idea.id);
		}

		if (idea.entity != null) {
			for (int counter = 0; counter < idea.entity.entityOrganizers.size(); counter++) {
				if (user.id == idea.entity.entityOrganizers.get(counter).id) {
					showIdeaForOrganizer(idea.id);
				}
			}
		}
		if (idea.entity != null && user.id == idea.entity.organization.lead.id) {
			showIdeaForOrganizer(idea.id);
		}
		if (idea.organization != null && idea.organization.lead.id == user.id) {
			showIdeaForOrganizer(idea.id);
		}
		// boolean hidingStatus = i.hide;
		boolean isSpammed = false;
		for (int counter = 0; counter < idea.ideaSpamReporter.size(); counter++) {
			if (user.id == idea.ideaSpamReporter.get(counter).id) {
				isSpammed = true;
			}
		}
		render(idea, isSpammed, user);
	}

	/**
	 * displays a page where the organizer can enter a justification Note for
	 * deleting/hiding idea
	 * 
	 * @param ideaId
	 *            id of idea to be deleted/hidden
	 * 
	 * @author Ghada Abu Shady
	 */

	public static void justificationNoteForOrganizer(Long ideaId) {
		Idea idea = Idea.findById(ideaId);
		String justificationNote = params.get("Note");
		render(idea, justificationNote);
	}

	/**
	 * displays the idea in a from for the organizer of the
	 * topic/entity/organization it is posted in Organizer can delete/hide idea
	 * through this page
	 * 
	 * @param ideaId
	 *            id of idea to be displayed
	 * 
	 * @author Ghada Abu Shady
	 */
	public static void showIdeaForOrganizer(Long ideaId) {
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		Idea idea = Idea.findById(ideaId);
		render(idea,user);
	}

	/**
	 * displays the ideas created by the user displaying it. he can tag/untag
	 * through this page
	 * 
	 * checks whether the idea has been marked as spam before and renders the
	 * boolean to the view.
	 * 
	 * @author Shahir El Faramawy
	 * 
	 * @param ideaId
	 *            id of idea to be displayed
	 * 
	 * @author Ghada Abu Shady
	 */

	public static void showUserIdea(Long ideaId) {

		String userIdString = session.get("userId");
		if (userIdString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(userIdString);
		User user = User.findById(userId);
		boolean userIsAdmin=false;
		if(user.email.equals("admin@admin.com")){
			userIsAdmin=true;
		}
		Idea idea = Idea.findById(ideaId);

		List<Tag> ideaOrganizationTags = new ArrayList();
		boolean userIsOrganizer = false;
		List<Tag> tagsIdeaNotTaggedIn = new ArrayList();

		String note = "";
		if (idea.topic != null) {
			ideaOrganizationTags = idea.topic.entity.organization.tags;
			if (user.id == idea.topic.author.id) {
				userIsOrganizer = true;
			}
			for (int counter = 0; counter < idea.topic.entity.entityOrganizers
					.size(); counter++) {
				if (user.id == idea.topic.entity.entityOrganizers.get(counter).id) {
					userIsOrganizer = true;
				}
			}
			if (user.id == idea.topic.entity.organization.lead.id) {
				userIsOrganizer = true;
			}

		} else {
			if (idea.entity != null) {
				ideaOrganizationTags = idea.entity.organization.tags;
				for (int counter = 0; counter < idea.entity.entityOrganizers
						.size(); counter++) {
					if (user.id == idea.entity.entityOrganizers.get(counter).id
							&& idea.author.id == idea.entity.entityOrganizers
									.get(counter).id) {
						userIsOrganizer = true;
						break;
					}
				}
				if (user.id == idea.entity.organization.lead.id) {
					userIsOrganizer = true;
				}

			} else {
				ideaOrganizationTags = idea.organization.tags;
				if (idea.organization.lead.id == user.id) {
					userIsOrganizer = true;
				}
			}
		}
		for (int counter = 0; counter < ideaOrganizationTags.size(); counter++) {
			boolean found = true;
			for (int secondCounter = 0; secondCounter < idea.tags.size(); secondCounter++) {
				if (idea.tags.get(secondCounter).id == ideaOrganizationTags
						.get(counter).id) {
					found = false;
					break;
				}

			}
			if (found == true) {
				tagsIdeaNotTaggedIn.add(ideaOrganizationTags.get(counter));
			}
		}
		boolean isSpammed = false;
		for (int counter = 0; counter < idea.ideaSpamReporter.size(); counter++) {
			if (user.id == idea.ideaSpamReporter.get(counter).id) {
				isSpammed = true;
			}
		}
		String tagString = "i" + idea.id;
		render(idea, user, userIsOrganizer, note, isSpammed,
				tagsIdeaNotTaggedIn, tagString,userIsAdmin);

	}

	/**
	 * changePriority sets the priority form the organizer picks to the idea and
	 * saves it
	 * 
	 * @param ideaId
	 * @param priority
	 * 
	 * @author Ahmed Ammar
	 */
	public static void changePriority(long ideaId, String priority) {
		Idea idea = Idea.findById(ideaId);
		idea.priority = priority;
		idea.save();

	}

	/**
	 * handles the actual adding of idea to topic and it checks duplicate and
	 * empty idea titles
	 * 
	 * @param topicId
	 *            topic id that idea will be inserted on
	 * @author Ghada Abu Shady
	 */
	public static void addIdeaToTopic(Long topicId) {
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		Topic topic = Topic.findById(topicId);
		List<Idea> compare = topic.ideas;
		String title = params.get("Title");
		for (int counter = 0; counter < compare.size(); counter++) {
			if (compare.get(counter).title.equals(title)) {
				handleDuplicateIdeasForTopics(topicId);
			}
		}

		String body = params.get("Body");
		Idea idea = topic.addIdeaToTopic(user, title, body).save();
		user.save();
		render(idea);
	}

	/**
	 * handles the actual adding of idea to entity and it checks duplicate
	 * and empty idea titles
	 * 
	 * @param entityId
	 *            entity id that idea will be inserted on
	 * @author Ghada Abu Shady
	 */
	public static void addIdeaToEntity(Long entityId) {
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		Entities entity = Entities.findById(entityId);
		List<Idea> compare = entity.AirIdeas;
		String title = params.get("Title");
		for (int counter = 0; counter < compare.size(); counter++) {
			if (compare.get(counter).title.equals(title)) {
				handleDuplicateIdeasForEntities(entityId);
			}
		}
		String body = params.get("Body");
		Idea idea = entity.addIdeaToEntity(user, title, body).save();
		user.save();
		render(idea);
	}

	/**
	 * handles the actual adding of idea to organization and it checks
	 * duplicate and empty idea titles
	 * 
	 * @param organizationId
	 *            organization id that idea will be inserted on
	 * @author Ghada Abu Shady
	 */
	public static void addIdeaToOrganization(Long organizationId) {
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		Organization organization = Organization.findById(organizationId);
		List<Idea> compare = organization.AirIdeas;
		String title = params.get("Title");
		for (int counter = 0; counter < compare.size(); counter++) {
			if (compare.get(counter).title.equals(title)) {
				handleDuplicateIdeasForOrganization(organization.id);
			}
		}

		String body = params.get("Body");
		Idea idea = organization.addIdeaToOrganization(user, title, body)
				.save();
		user.save();
		render(idea);
	}

	/**
	 * handles the duplicate inserted idea titles
	 * 
	 * @param topicId
	 *            topic that idea will be inserted on
	 * @author Ghada Abu Shady
	 */
	public static void handleDuplicateIdeasForTopics(Long topicId) {
		Topic topic = Topic.findById(topicId);
		render(topic);
	}

	/**
	 * handles the duplicate inserted idea titles
	 * 
	 * @param entityId
	 *            entity that idea will be inserted on
	 * @author Ghada Abu Shady
	 */
	public static void handleDuplicateIdeasForEntities(Long entityId) {
		Entities entity = Entities.findById(entityId);
		render(entity);
	}

	/**
	 * handles the duplicate inserted idea titles
	 * 
	 * @param organizationId
	 *            organization that idea will be inserted on
	 * @author Ghada Abu Shady
	 */
	public static void handleDuplicateIdeasForOrganization(Long organizationId) {
		Organization organization = Organization.findById(organizationId);
		render(organization);
	}

	/**
	 * displays the list of ideas that belong to the user
	 * 
	 * @author Ghada Abu Shady
	 */
	public static void showUserIdeas() {
		String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User user = User.findById(userId);
		List<Idea> IdeaList = Idea.findAll();
		List<Idea> ideas = new ArrayList<Idea>();
		for (int counter = 0; counter < IdeaList.size(); counter++) {
			if (user.id == IdeaList.get(counter).author.id) {
				ideas.add(IdeaList.get(counter));
			}
		}

		render(ideas);

	}

	/**
	 * performs the action of hiding Idea
	 * 
	 * @param ideaId
	 *            the id of idea to be hidden
	 * @author Ghada Abu Shady
	 */

	public static void hideIdea(Long ideaId) {
		Idea idea = Idea.findById(ideaId);
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		idea.hidePerformer = "" + user.id;
		List<User> ideaAuthor = new ArrayList<User>();
		ideaAuthor.add(idea.author);
		String justificationNote = params.get("Note");

		if (user.id == idea.author.id) {
			idea.hide = true;
			idea.save();
			render(idea, idea.hidePerformer);
		} else {

			if (idea.topic != null) {
				user.sendNotificationWithType("Your idea '" + idea.title
						+ "' has been hidden by Topic" + "(" + idea.topic.title
						+ ")" + " Organizer" + "\n" + "Justification Note: "
						+ "\n" + justificationNote, ideaAuthor, "Idea", idea.id);
				idea.hide = true;
				idea.save();
				render(idea, idea.hidePerformer);

			} else {
				if (idea.entity != null) {
					user.sendNotificationWithType("Your idea '" + idea.title
							+ "' has been hidden by Entity" + "("
							+ idea.entity.entityName + ")" + " Organizer"
							+ "\n" + "Justification Note: " + "\n"
							+ justificationNote, ideaAuthor, "Idea", idea.id);
					idea.hide = true;
					idea.save();
					render(idea, idea.hidePerformer);
				} else {
					user.sendNotificationWithType(
							"Your idea '" + idea.title
									+ "' has been hidden by Organization" + "("
									+ idea.organization.name + ")" + " Lead"
									+ "\n" + "Justification Note: " + "\n"
									+ justificationNote, ideaAuthor, "Idea",
							idea.id);

					idea.hide = true;
					idea.save();
					render(idea, idea.hidePerformer);
				}
			}
		}
	}

	/**
	 * performs the action of unhiding Idea
	 * 
	 * @param ideaId
	 *            the id of idea to be unhidden
	 * 
	 * @author Ghada Abu Shady
	 */

	public static void unhideIdea(Long ideaId) {
		Idea idea = Idea.findById(ideaId);
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		List<User> ideaAuthor = new ArrayList<User>();
		idea.hidePerformer = "" + user.id;
		ideaAuthor.add(idea.author);
		if (user.id == idea.author.id) {
			idea.hide = false;
			idea.save();
			render(idea, idea.hidePerformer);
		} else {

			if (idea.topic != null) {
				user.sendNotificationWithType("Your idea '" + idea.title
						+ "' has been unhidden by Topic" + "("
						+ idea.topic.title + ")" + " Organizer", ideaAuthor,
						"Idea", idea.id);
				idea.hide = false;
				idea.save();
				render(idea, idea.hidePerformer);

			} else {
				if (idea.entity != null) {
					user.sendNotificationWithType("Your idea '" + idea.title
							+ "' has been unhidden by Entity" + "("
							+ idea.entity.entityName + ")" + " Organizer",
							ideaAuthor, "Idea", idea.id);
					idea.hide = false;
					idea.save();
					render(idea, idea.hidePerformer);
				} else {
					user.sendNotificationWithType("Your idea '" + idea.title
							+ "' has been unhidden by Organization" + "("
							+ idea.organization.name + ")" + " Lead",
							ideaAuthor, "Idea", idea.id);

					idea.hide = false;
					idea.save();
					render(idea, idea.hidePerformer);
				}
			}
		}
	}

	/**
	 * displays the hidden ideas
	 * 
	 * @author Ghada Abu Shady
	 */
	public static void showHiddenIdeas() {
		List<Idea> ideaList = Idea.findAll();
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		List<Idea> hiddenIdeaList = new ArrayList<Idea>();

		for (int counter = 0; counter < ideaList.size(); counter++) {
			if (ideaList.get(counter).hide == true
					&& ideaList.get(counter).hidePerformer.equals(id)) {
				hiddenIdeaList.add(ideaList.get(counter));
			}
		}

		render(hiddenIdeaList, user);
	}

	/**
	 * deletes the idea of an Idea developer it handles deletion of idea from
	 * database, tags it is tagged in, user ideas, topic/entity/organization it
	 * is found in, list of communities it is found in. it also deletes comments
	 * of this idea from database it decrements the user counter of contribution
	 * 
	 * @param ideaId
	 *            the id of the idea to be deleted
	 * 
	 * @author Ghada Abu Shady
	 */

	public static void deleteIdea(Long ideaId) {
		Idea idea = Idea.findById(ideaId);
		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		List<User> ideaAuthor = new ArrayList<User>();
		ideaAuthor.add(idea.author);
		String justificationNote = params.get("Note");

		for (int counter = 0; counter < idea.tags.size(); counter++) {
			idea.tags.get(counter).Ideas.remove(idea);
			idea.tags.get(counter).save();
		}

		idea.author.idea.remove(idea);
		idea.author.contributionCounter--;

		if (idea.topic != null) {
			Topic ideaTopic = idea.topic;
			ideaTopic.ideas.remove(idea);
			idea.delete();
			if (idea.author.id != user.id) {
				user.sendNotificationWithType("Your idea '" + idea.title
						+ "' has been deleted by Topic" + "("
						+ idea.topic.title + ")" + " Organizer" + "\n"
						+ "Justification Note: " + "\n" + justificationNote,
						ideaAuthor, "Idea", idea.id);
			}
			render(ideaTopic);

		} else {
			if (idea.entity != null) {
				Entities ideaEntity = idea.entity;
				ideaEntity.AirIdeas.remove(idea);
				idea.delete();
				if (idea.author.id != user.id) {
					user.sendNotificationWithType("Your idea '" + idea.title
							+ "' has been deleted by Entity" + "("
							+ idea.entity.entityName + ")" + " Organizer"
							+ "\n" + "Justification Note: " + "\n"
							+ justificationNote, ideaAuthor, "Idea", idea.id);

				}
				render(ideaEntity);
			} else {
				Organization ideaOrganization = idea.organization;
				ideaOrganization.AirIdeas.remove(idea);
				idea.delete();
				if (idea.author.id != user.id) {
					user.sendNotificationWithType(
							"Your idea '" + idea.title
									+ "' has been deleted by Organization"
									+ "(" + idea.organization.name + ")"
									+ " Lead" + "\n" + "Justification Note: "
									+ "\n" + justificationNote, ideaAuthor,
							"Idea", idea.id);
				}

				render(ideaOrganization);
			}
		}

	}

	/**
	 * displays the list of ideas that belong to the an organization.
	 * 
	 * rendering size ,organization and merger to HTML, Idea priority for organizer
	 * and organization lead.
	 * 
	 * @param organizationId
	 *            organization that its ideas will be shown
	 * @author Ghada Abu Shady
	 * @author youstina galal
	 * @author Ahmed Ammar
	 */
	public static void showOrgIdeas(Long organizationId) {
		if (idea.size() > 0) {
			idea.clear();
		}
		System.out.println("ideaaaa" + idea.size());
		organizationIdOne = organizationId;
		String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User merger = User.findById(userId);
		System.out.println(merger.name);
		Organization organization = Organization.findById(organizationId);
		List<Idea> listIdea = organization.AirIdeas;
		System.out.println(listIdea.size());

		int size = organization.AirIdeas.size();
		Permission permission = User.userPermissionInOrganization(userId, organization.id);
		String role = permission.aUserType;
		
		boolean isIdeaDeveloper;
		if(role.matches("ideaDeveloper")){
			isIdeaDeveloper = true;
		} else {
			isIdeaDeveloper = false;
		}


		render(listIdea, organization, merger, size, idea, isIdeaDeveloper);

	}

	/**
	 * takes a idea id, retrieves the idea and the User that marked the idea as
	 * spamed and will set the idea to spamed using the spamIdea method from the
	 * model.
	 * 
	 * @param id
	 *            The id of idea
	 * 
	 * 
	 * @author Shahir El Faramawy
	 */
	public static void showIdeaSpam(Long id) throws EmailException {
		String temp = session.get("userId");
		if (temp == null) {
			Home.home(null, null, "Please Login");
		}
		Long idTemp = Long.parseLong(temp);
		User spamer = User.findById(idTemp);
		Idea spammed = Idea.findById(id);
		spammed.spamIdea(spamer);
		showUserIdea(id);

	}

	/**
	 * ShowIdeaAsDuplicate method gets the idea by the id and mark it as
	 * duplicate if the organization lead approved the request sent by the
	 * ideadeveloper to consider if idea is duplicate and also sends an e-mail
	 * to the organization lead to tell him that his idea has been marked as
	 * duplicate.
	 * 
	 * @param Id
	 *            id of the idea that will be marked as duplicate.
	 * @throws EmailException
	 * @author Nada Hassan
	 */
	public static void showIdeaAsDuplicate(Long id) throws EmailException {
		
		String temp = session.get("userId");
		Long idTemp = Long.parseLong(temp);
		User user = User.findById(idTemp);
	//	Organization organization = Organization.findById(orgId);
		Idea originalIdea = Idea.findById(id);
	//	Idea duplicateIdea = Idea.findById(orgId);
		originalIdea.ConfirmAsDuplicate(user);
	    String body1=params.get("body");
//	    List<Idea> ideaList = Idea.findAll();
//	    for(int i=0;i < ideaList.size();i++){
//	    	if (ideaList.get(i).body == originalIdea.body){
//	    		isDuplicate=true;
//	    		ideaList.get(i).merge = true;
//	    	ideaList.get(i).merge();
//	    	}}
	    showUserIdea(id);
	    }
		

	

	/**
	 * displays the list of ideas that belong to a certain topic.
	 * 
	 * 
	 * rendering size ,organization and merger to HTML.
	 * 
	 * 
	 * @param topicId
	 *            id of topic its ideas will be shown
	 * @author Ghada Abu Shady
	 * @author youstina galal
	 */

	public static void showTopicIdeas(Long topicId) {
		if (idea.size() > 0) {
			idea.clear();
		}
		topicIdOne = topicId;
		Topic topic = Topic.findById(topicId);
		System.out.println(topicId);
		String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User merger = User.findById(userId);
		System.out.println(merger.email);
		List<Idea> ideaList = topic.ideas;
		int size = topic.ideas.size();
		render(ideaList, topic, merger, size);

	}

	/**
	 * displays the list of ideas that belong to a certain entity.
	 * 
	 * has a loop to handle permissions to check whether the user in session is
	 * an organizer. and renders the user in session,size,entity author if
	 * exists.
	 * 
	 * @param entityId
	 *            id of entity
	 * @author Ghada Abu Shady
	 * @author youstina galal
	 */

	public static void showEntityIdeas(Long entityId) {
		if (idea.size() > 0) {
			idea.clear();
		}
		entityIdOne = entityId;
		System.out.println(entityId );
		Entities entity = Entities.findById(entityId);
		System.out.println(entity.entityName);
		System.out.println(idea.size() + "sds");

		Organization organization = entity.organization;
		System.out.println(organization.id );
		System.out.println(entityIdOne);
		String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User merger = User.findById(userId);

		List<Idea> ideaList = entity.AirIdeas;

		int size = entity.AirIdeas.size();
		List<User> mergers = entity.entityOrganizers;

		System.out.println(mergers.size() );
		boolean isOrganizer = false;
		for (int counter = 0; counter < mergers.size(); counter++) {

			
			if (merger.email == mergers.get(counter).email) {
				isOrganizer=true;
			} 

			User author = User.findById(mergers.get(counter).id);
			System.out.println(author.email );
			if (merger.email == author.email) {
				System.out.println(entity.entityName );
				render(ideaList, merger, size, author, entity);
			} else {
				render(ideaList, merger, size, author, entity);
			}

		}
		User author = entity.organization.lead;
		render(ideaList, merger, size, author, idea, entity,isOrganizer );

	}

	/**
	 * renders the air ideas Homepage.
	 * 
	 * checks whether selectedIdea list is empty or not,so that whenever the
	 * user browse this page ,the list will be empty it.
	 * 
	 * checks whether the user of the system is the organization lead or not
	 * 
	 * @param organizationId
	 *            to get the ideas of specific organization
	 * @author Ghada Abu Shady
	 * @author Mohamed Abdel Kader
	 * @author youstina galal
	 */

	public static void showOrgIdeasHome(Long organizationId) {

		String id = session.get("userId");
		if (id == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(id);
		User user = User.findById(userId);
		Organization organization = Organization.findById(organizationId);
		boolean isLead = false;
		if (organization.lead.id == user.id) {
			isLead = true;
		}
		if (idea.size() > 0) {
			idea.clear();
		}
		boolean userIsAdmin = false;
		
		if(user.email.equals("admin@admin.com")){
			userIsAdmin=true;
		}
		
		render(organizationId, isLead,userIsAdmin);
	}

	/**
	 * gets a list of params which is a list of Idea that is checked ,the user
	 * through session to check whether he is lead or not(permissions) ,gets
	 * also the users of the idea to send them notifications.
	 * 
	 * @author youstina galal
	 */
	public static void selectAllIdeas() {
		try {

			Organization orgainzation = Organization
					.findById(organizationIdOne);
			String[] input = params.getAll("box");
			for (int counter = 0; counter < input.length; counter++) {
				String idRetrieve = "";
				for (int firstCounter = 0; firstCounter < input[counter]
						.length(); firstCounter++) {
					if (input[counter].charAt(firstCounter) >= '0'
							&& input[counter].charAt(firstCounter) <= '9') {
						idRetrieve += input[counter].charAt(firstCounter);
					}
				}
				Long id = Long.parseLong(idRetrieve);
				Idea ideaY = Idea.findById(id);
				ideaY.save();
				ideaY.merge = true;
				System.out.println(ideaY.merge);
				idea.add(ideaY);
				System.out.println(idea.get(counter).body);

			}
			if (input.length > 1) {
				if (input.length == idea.size()) {
					System.out.println(idea.size());
					String idString = session.get("userId");
					if (idString == null) {
						Home.home(null, null, "Please Login");
					}
					Long userId = Long.parseLong(idString);
					User merger = User.findById(userId);
					ArrayList<User> users = new ArrayList<User>();
					for (int iCounter = 0; iCounter < idea.size(); iCounter++) {
						System.out.println(idea.size() );
						System.out.println(orgainzation.email);
						if (merger.email == orgainzation.lead.email) {
							Idea ideaOne = idea.get(iCounter);
							users.add(ideaOne.author);
							System.out.println(ideaOne.body);

							merger.sendNotificationWithType("your idea" + " "
									+ ideaOne.body + " " + "has been merged",
									users, "Idea", ideaOne.id);
						}

					}

					showOrganiationIdeasMerged();
				} else {
					handleDuplicateIdeasForOrganization(organizationIdOne);
				}
			} else {
				showOrgIdeas(organizationIdOne);
			}

		} catch (NullPointerException error) {
			Requests.contentNotFound();
		}

	}

	/**
	 * renders list of idea that was checked to HTML
	 * 
	 * @author youstina galal
	 */
	public static void showOrganiationIdeasMerged() {
		System.out.println(organizationIdOne);
		Organization organization = Organization.findById(organizationIdOne);
		List<Idea> ideaZ = idea;
		System.out.println(idea.size());
		render(ideaZ, organization, idea);
	}

	/**
	 * gets the user through session,find the organization using ID,and takes
	 * new title and new body as an input from the user by cutting and pasting
	 * the old edited ideas,then it deletes the old ideas from organization list
	 * of ideas by calling deleteListOfIdeas(ids)
	 * 
	 * @author youstina galal
	 */
	public static void continueOrgainzationIdeasMerging(Long organizationId) {
		String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User merger = User.findById(userId);
		System.out.println(organizationId);
		List<Long> ids = new ArrayList<Long>();
		for (int jCounter = 0; jCounter < idea.size(); jCounter++) {
			System.out.println(idea.size());
			System.out.println("ok");
			if (idea.get(jCounter).merge == true) {
				System.out.println("ok");
				ids.add(idea.get(jCounter).id);
				System.out.println(idea.get(jCounter).title );

			}
		}

		System.out.println(ids.size());

		String title = params.get("Title");

		System.out.println("the" + title + "");
		String body = params.get("Body");
		deleteListOfIdeas(ids, title, body, merger.id);

	}

	/**
	 * takes a list of ideaId,find each idea,check whether it was posted in
	 * topic,entity or orgainzation delete it ,then return user to the main list
	 * of ideas.
	 * @param IdeaId
	 *            list of ideas id that will be deleted in the method
	 * @param title
	 *            title of new idea that will be created
	 * @param body
	 *            body of new idea 
	 * @param userId
	 *            author of the idea
	 * 
	 * @author youstina galal
	 */
	public static void deleteListOfIdeas(List<Long> ideaId, String title,
			String body, Long userId) {
		try {
			User user = User.findById(userId);
			Long ideaIdOne = ideaId.get(0);
			Idea ideaOne = Idea.findById(ideaIdOne);
			if (ideaOne.topic != null) {
				Topic topic = Topic.findById(topicIdOne);
				for (int counterX = 0; counterX < ideaId.size(); counterX++) {
					Idea idea = Idea.findById(ideaId.get(counterX));
					idea.author.idea.remove(idea);
					idea.author.contributionCounter--;
					Topic ideaTopic = idea.topic;
					ideaTopic.ideas.remove(idea);
					idea.delete();
				}
				Idea ideaX = topic.addIdeaToTopic(user, title, body).save();
				System.out.println(ideaX.body);

				ideaX.save();

				showTopicIdeas(topic.id);

			} else {
				if (ideaOne.entity != null) {
					Entities entity = Entities.findById(entityIdOne);
					for (int counter = 0; counter < ideaId.size(); counter++) {
						Idea idea = Idea.findById(ideaId.get(counter));
						idea.author.idea.remove(idea);
						idea.author.contributionCounter--;
						Entities ideaEntity = idea.entity;
						ideaEntity.AirIdeas.remove(idea);
						idea.delete();
					}
					Idea ideaX = entity.addIdeaToEntity(user, title, body)
							.save();
					System.out.println(ideaX.body);

					ideaX.save();

					showEntityIdeas(entity.id);

				} else {
					Organization orgainzation = Organization
							.findById(organizationIdOne);
					for (int counter = 0; counter < ideaId.size(); counter++) {
						Idea idea = Idea.findById(ideaId.get(counter));
						idea.author.idea.remove(idea);
						idea.author.contributionCounter--;
						Organization ideaOrganization = idea.organization;
						ideaOrganization.AirIdeas.remove(idea);
						idea.delete();
					}
					Idea ideaX = orgainzation.addIdeaToOrganization(user,
							title, body).save();
					System.out.println(ideaX.body);

					ideaX.save();

					showOrgIdeas(orgainzation.id);
				}
			}
		} catch (NullPointerException error) {
			Requests.contentNotFound();
		}

	}

	/**
	 * gets a list of params which is a list of Idea that is checked ,the user
	 * through session to check whether he is lead or not(permissions) ,gets
	 * also the users of the idea to send them notifications.
	 * 
	 * @author youstina galal
	 */

	public static void selectAllTopicIdeas() {
		try {
			String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User merger = User.findById(userId);

			Topic topic = Topic.findById(topicIdOne);
			Organization orgainzation = topic.entity.organization;
			Entities entity = topic.entity;
			System.out.println(topicIdOne + "topicId");
			String[] input = params.getAll("box");
			for (int counter = 0; counter < input.length; counter++) {
				String idRetrieve = "";
				for (int xCounter = 0; xCounter < input[counter].length(); xCounter++) {
					if (input[counter].charAt(xCounter) >= '0'
							&& input[counter].charAt(xCounter) <= '9') {
						idRetrieve += input[counter].charAt(xCounter);
					}
				}
				Long id = Long.parseLong(idRetrieve);
				Idea ideaW = Idea.findById(id);
				System.out.println(ideaW.body);
				ideaW.save();
				ideaW.merge = true;
				System.out.println(ideaW.merge);
				idea.add(ideaW);
				System.out.println(idea.get(counter).body);
			}
			if (input.length > 1) {
				if (input.length == idea.size()) {
					System.out.println(idea.size());
					System.out.println(idea.size());
					System.out.println(merger.email);
					ArrayList<User> users = new ArrayList<User>();
					for (int iCounter = 0; iCounter < idea.size(); iCounter++) {
						System.out.println(idea.size() );
						if (topic.id == topicIdOne) {
							if (orgainzation.id == organizationIdOne) {
								if (entity.id == entityIdOne) {
									System.out.println(orgainzation.email);
									if (merger.email == orgainzation.lead.email) {

										Idea ideaOne = idea.get(iCounter);
										users.add(ideaOne.author);
										System.out.println(ideaOne.body
												+ "good");

										merger.sendNotificationWithType(
												"your idea" + " "
														+ ideaOne.body + " "
														+ "has been merged",
												users, "Idea", ideaOne.id);
									}
								}
							}
						}
					}

					showTopicIdeasMerged();
				} else {
					handleDuplicateIdeasForOrganization(organizationIdOne);
				}
			} else {
				showTopicIdeas(topicIdOne);
			}
			}

		 catch (NullPointerException error) {
			Requests.contentNotFound();
		}

	}

	/**
	 * renders list of idea that was checked to HTML
	 * 
	 * @author youstina galal
	 */
	public static void showTopicIdeasMerged() {
		System.out.println(topicIdOne );
		Topic topic = Topic.findById(topicIdOne);
		List<Idea> listOfIdeas = idea;
		// System.out.println(idea.size());
		render(listOfIdeas, topic);
	}

	/**
	 * gets the user through session,find the topic using ID,and takes new title
	 * and new body as an input from the user by cutting and pasting the old
	 * edited ideas,then it deletes the old ideas from topic list of ideas by
	 * calling deleteListOfIdeas(ids).
	 * @param topicId
	 *           id of the topic that we want to merge it's ideas
	 * @author youstina galal
	 */

	public static void continueTopicIdeasMerging(Long topicId) {
		String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User merger = User.findById(userId);
		System.out.println(topicId);

		List<Long> ids = new ArrayList<Long>();
		for (int counter = 0; counter < idea.size(); counter++) {
			System.out.println(idea.size());
			//System.out.println("sBASJK");
			if (idea.get(counter).merge == true) {
				ids.add(idea.get(counter).id);
				System.out.println(idea.get(counter).title );
			}
		}
		System.out.println(ids.size());
		String title = params.get("Title");
		System.out.println("the" + title + "");
		String body = params.get("Body");
		deleteListOfIdeas(ids, title, body, merger.id);
	}

	/**
	 * gets a list of params which is a list of Idea that is checked ,the user
	 * through session to check whether he is lead or not(permissions) ,gets
	 * also the users of the idea to send them notifications.
	 * 
	 * @author youstina galal
	 */

	public static void selectAllEntityIdeas() {
		try {

			System.out.println(entityIdOne + "done");
			Entities entity = Entities.findById(entityIdOne);
			Organization orgainzation = entity.organization;

			System.out.println(entityIdOne );
			String[] input = params.getAll("box");
			for (int counterC = 0; counterC < input.length; counterC++) {
				String idRetrieve = "";
				for (int counter = 0; counter < input[counterC].length(); counter++) {
					if (input[counterC].charAt(counter) >= '0'
							&& input[counterC].charAt(counter) <= '9') {
						idRetrieve += input[counterC].charAt(counter);
					}
				}
				Long id = Long.parseLong(idRetrieve);
				Idea ideaS = Idea.findById(id);
				System.out.println(ideaS.body);
				ideaS.save();
				ideaS.merge = true;
				System.out.println(ideaS.merge);
				idea.add(ideaS);
				System.out.println(idea.get(counterC).body);

			}
			if (input.length > 1) {
				if (input.length == idea.size()) {

					String idString = session.get("userId");
					if (idString == null) {
						Home.home(null, null, "Please Login");
					}
					Long userId = Long.parseLong(idString);
					User merger = User.findById(userId);
					System.out.println(idea.size());
					System.out.println(merger.email);
					ArrayList<User> users = new ArrayList<User>();
					for (int iCounter = 0; iCounter < idea.size(); iCounter++) {
						System.out.println(idea.size() );

						System.out.println(orgainzation.email);
						if (entity.id == entityIdOne) {
							if (merger.email == orgainzation.lead.email) {
								Idea ideaOne = idea.get(iCounter);
								users.add(ideaOne.author);
								System.out.println(ideaOne.body );

								merger.sendNotificationWithType("your idea"
										+ " " + ideaOne.body + " "
										+ "has been merged", users, "Idea",
										ideaOne.id);

							}
						}

					}

					showEntityIdeasMerged();
				} else {
					handleDuplicateIdeasForOrganization(organizationIdOne);
				}
			} else {
				showEntityIdeas(entityIdOne);
			}

		} catch (NullPointerException error) {
			Requests.contentNotFound();
		}

	}

	/**
	 * renders list of idea that was checked to HTML
	 * 
	 * @author youstina galal
	 */
	public static void showEntityIdeasMerged() {
		// System.out.println(entityIdd + "dbhqwedjh");
		Entities entity = Entities.findById(entityIdOne);
		List<Idea> listOfIdeas = idea;
		// System.out.println(idea.size());
		render(listOfIdeas, entity);
	}

	/**
	 * gets the user through session,find the topic using ID,and takes new title
	 * and new body as an input from the user by cutting and pasting the old
	 * edited ideas,then it deletes the old ideas from entity list of ideas by
	 * calling deleteListOfIdeas(ids).
	 * param entityId
	 *           id of the entity that we need to merge it's ideas
	 * 
	 * @author youstina galal
	 */

	public static void continueEntityIdeasMerging(Long entityId) {
		String idString = session.get("userId");
		if (idString == null) {
			Home.home(null, null, "Please Login");
		}
		Long userId = Long.parseLong(idString);
		User merger = User.findById(userId);
		List<Long> ids = new ArrayList<Long>();
		for (int count = 0; count < idea.size(); count++) {
			if (idea.get(count).merge == true) {
				// System.out.println("dis");
				ids.add(idea.get(count).id);
			}
		}
		System.out.println(ids.size());
		// deleteListOfIdeas(ids);
		String title = params.get("Title");
		System.out.println("x" + title + "");
		String body = params.get("Body");
		deleteListOfIdeas(ids, title, body, merger.id);

	}

	

}
